/**
 * 2017年12月20日
 */
package com.cmwa.scbp.sys.msg.filter.filters;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.cmwa.scbp.sys.msg.dao.IMsgSendDao;
import com.cmwa.scbp.sys.msg.filter.MsgFilter;
import com.cmwa.scbp.sys.msg.filter.MsgFilterChain;
import com.cmwa.scbp.sys.msg.filter.MsgFilterResult;
import com.cmwa.scbp.sys.msg.filter.enums.MsgFilterCodeEnum;
import com.cmwa.scbp.sys.msg.vo.ManualOperationParamsVo;
import com.cmwa.scbp.sys.msg.vo.MsgWaitSendVo;
import com.cmwa.scbp.utils.JsonUtil;
import com.google.common.base.Joiner;

/**
 * 标题和收件人重复的消息过滤器
 * @author ex-zuotc
 * 2017年12月20日
 */
@Component("titleAndRecipientsDuplicateFilter")
public class TitleAndRecipientsDuplicateFilter implements MsgFilter {
	
	private static Logger logger = LoggerFactory.getLogger(TitleAndRecipientsDuplicateFilter.class); 
	
	@Resource
	private IMsgSendDao iMsgSendDao;

	@Override
	public void doFilter(List<MsgWaitSendVo> sendVos, ManualOperationParamsVo params, String filterParam, MsgFilterChain filterChian) {
		logger.error("filterParam:" + filterParam);
		MsgFilterResult msgFilterResult = filterChian.getMsgFilterResult();
		
		@SuppressWarnings("unchecked")
		Map<String, Object> paramMap = JsonUtil.parseJson(filterParam, Map.class);
		// 多少分钟
		Integer minute = (Integer) paramMap.get("minute");
		
		for (MsgWaitSendVo sendVo : sendVos) {
			List<String> recipients = sendVo.getRecipients();
			String recipientsStr = Joiner.on(";").join(recipients);
			int sentCount = iMsgSendDao.getEmailTitleAndRecipientCount(sendVo.getTitle(), recipientsStr, minute);
			if (sentCount != 0) {
				msgFilterResult.setSendable(false);
				msgFilterResult.setFilterCode(MsgFilterCodeEnum.M008_1);
				msgFilterResult.setMessage("邮件《" + sendVo.getTitle() + "》，收件人：" + recipientsStr + "，" + minute + "分钟内重复发送。");
				return;
			}
		}
		
		// next
		filterChian.doFilter(sendVos, params);
	}

}
